﻿using System;

namespace Calculator
{
    class Calculator
    {
        public static double DoOperation(double num1, double num2, string op)
        {
            double result = double.NaN;
            switch (op)
            {
                case "a":
                    result = num1 + num2;
                    break;
                case "s":
                    result = num1 - num2;
                    break;
                case "m":
                    result = num1 * num2;
                    break;
                case "d":
                    if (num2 != 0)
                    {
                        result = num1 / num2;
                    }
                    break;
                default:
                    break;
            }
            return result;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            bool endApp = false;
            Console.WriteLine("C#计算器\r");
            Console.WriteLine("--------\n");

            while (!endApp)
            {
                string numInput1 = "";
                string numInput2 = "";
                double result = 0;
                Console.Write("请输入一个数字：");
                numInput1 = Console.ReadLine();
                double cleanNum1 = 0;
                while (!double.TryParse(numInput1, out cleanNum1))
                {
                    Console.Write("这不是一个有效输入，请输入一个数字：");
                    numInput1 = Console.ReadLine();
                }
                Console.Write("请输入另一个数字：");
                numInput2 = Console.ReadLine();
                double cleanNum2 = 0;
                while (!double.TryParse(numInput2, out cleanNum2))
                {
                    Console.Write("这不是一个有效输入，请输入一个数字：");
                    numInput2 = Console.ReadLine();
                }
                Console.WriteLine("请选择一种运算");
                Console.WriteLine("\ta - 加法");
                Console.WriteLine("\ts - 减法");
                Console.WriteLine("\tm - 乘法");
                Console.WriteLine("\td - 除法");
                string op = Console.ReadLine();
                try
                {
                    result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
                    if (double.IsNaN(result))
                    {
                        Console.WriteLine("结果错误。\n");
                    }
                    else Console.WriteLine("运算结果： {0:0.##}\n", result);
                }
                catch (Exception e)
                {
                    Console.WriteLine("试图运算时发生了异常\n - 细节： " + e.Message);
                }
                Console.WriteLine("------------------------\n");
                Console.Write("按n键退出程序，或其它任意按键继续进行运算 ");
                if (Console.ReadLine() == "n") endApp = true;
                Console.WriteLine("\n");
            }
            return;
        }
    }
}

